//
//  JKFileExplorerWebViewController.m
//  Baisi
//
//  Created by albert on 2018/11/8.
//  Copyright © 2018 安永博. All rights reserved.
//

#import "JKFileExplorerWebViewController.h"

@interface JKFileExplorerWebViewController ()
{
    WKWebView *_webView;
    UIProgressView *_loadProgressView;
}


/** pop回调 */
@property (nonatomic, copy, readonly) void (^callBackBlock)(NSDictionary *callBackDataDict);
@end

@implementation JKFileExplorerWebViewController


/**
 * 加载网页类方法
 * urlStr   : 要加载的网页url
 * navTitle : 导航栏标题。如传nil则默认是网页本身的标题
 * pushedVc : 从哪个控制器push，传空则自己处理
 * callBackBlock : 回调
 */
+ (instancetype)loadUrlWithUrlStr:(NSString *)urlStr navTitle:(NSString *)navtitle pushedVc:(UIViewController *)pushedVc callBackBlock:(void(^)(NSDictionary *callBackparamDict))callBackBlock{
    
    if (!urlStr || [urlStr isEqual:[NSNull null]] || [urlStr isEqualToString:@""]) {
        
        return nil;
    }
    
    if (![NSURL URLWithString:urlStr]) {
        return nil;
    }
    
    JKFileExplorerWebViewController *vc = [[self alloc] init];
    
    vc.urlString = urlStr;
    vc.navigationItem.title = navtitle;
    
    if (pushedVc) {
        
        [pushedVc.navigationController pushViewController:vc animated:YES];
        
        return vc;
    }
    
    vc->_callBackBlock = callBackBlock;
    
    return vc;
}

/**
 * 加载网页类方法
 * URL      : 要加载的网页URL
 * navTitle : 导航栏标题。如传nil则默认是网页本身的标题
 * pushedVc : 从哪个控制器push，传空则自己处理
 * callBackBlock : 回调
 */
+ (instancetype)loadUrlWithURL:(NSURL *)URL navTitle:(NSString *)navtitle pushedVc:(UIViewController *)pushedVc callBackBlock:(void(^)(NSDictionary *callBackparamDict))callBackBlock{
    
    if (!URL) {
        
        return nil;
    }
    
    JKFileExplorerWebViewController *vc = [[self alloc] init];
    vc.URL = URL;
    vc.navigationItem.title = navtitle;
    
    if (pushedVc) {
        
        [pushedVc.navigationController pushViewController:vc animated:YES];
        
        return vc;
    }
    
    vc->_callBackBlock = callBackBlock;
    
    return vc;
}

#pragma mark - 懒加载
- (WKWebView *)webView{
    if (!_webView) {
        // 解决内存泄露问题
        WKWebViewConfiguration*config = [[WKWebViewConfiguration alloc]init];
        config.selectionGranularity = WKSelectionGranularityCharacter;
        
        // 让网页内容自适应大小
        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        config.userContentController = wkUController;
        
        // 创建WKWebView
        WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
        
        webView.frame = CGRectMake(0, JKNavBarHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - JKNavBarHeight);
        webView.navigationDelegate = self;
        webView.UIDelegate = self;
        webView.scrollView.delegate = self;
        webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, JKCurrentHomeIndicatorHeight, 0);
        [self.view insertSubview:webView atIndex:0];
        _webView = webView;
    }
    return _webView;
}

- (UIProgressView *)loadProgressView{
    if (!_loadProgressView) {
        UIProgressView *progressView = [[UIProgressView alloc] init];
        
        progressView.clipsToBounds = YES;
        progressView.frame = CGRectMake(0, JKNavBarHeight, [UIScreen mainScreen].bounds.size.width, 2);
        progressView.progressTintColor = [UIColor redColor];
        progressView.trackTintColor = [UIColor clearColor];
        [self.view addSubview:progressView];
        
        _loadProgressView = progressView;
    }
    return _loadProgressView;
}

#pragma mark - KVO
// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] floatValue];
        NSLog(@"加载进度-->%.2f", newprogress);
        
        if (newprogress >= 1) {
            !self.loadFinishedBlock ? : self.loadFinishedBlock(self);
            [self.loadProgressView setProgress:1.0 animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [UIView animateWithDuration:0.25 animations:^{
                    self.loadProgressView.alpha = 0;
                    
                } completion:^(BOOL finished) {
                    
                    [self.loadProgressView setProgress:0 animated:NO];
                }];
            });
            
        }else {
            self.loadProgressView.alpha = 1;
            [self.loadProgressView setProgress:newprogress animated:YES];
        }
    }
    
    //    if (object == self.webView && [keyPath isEqualToString:@"canGoBack"]) {
    //        BOOL canGoBack = [[change objectForKey:NSKeyValueChangeNewKey] boolValue];
    //        !self.canGoBackBlock ? : self.canGoBackBlock(canGoBack);
    //    }
}

#pragma mark - 初始化
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"back" style:(UIBarButtonItemStylePlain) target:self action:@selector(back)];
    
    // 防止scrollView拦截右划返回手势
    UIView *leftView = [[UIView alloc] init];
    leftView.backgroundColor = [UIColor clearColor];
    leftView.frame = CGRectMake(0, JKNavBarHeight, 8, self.view.frame.size.height - JKNavBarHeight);
    [self.view addSubview:leftView];
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:(NSKeyValueObservingOptionNew) context:nil];
    
    //    [self.webView addObserver:self forKeyPath:@"canGoBack" options:(NSKeyValueObservingOptionNew) context:nil];
    
    // 优先加载URL
    if (self.data) {
        
        if (@available(iOS 9.0, *)) {
            
            // application/octet-stream 代表任意的二进制数据
            [self.webView loadData:self.data MIMEType:@"application/octet-stream" characterEncodingName:@"UTF-8" baseURL:[NSURL new]];
            
        } else {
            
        }
        
        return;
    }
    
    // 优先加载URL
    if (self.URL) {
        
        [self.webView loadRequest:[NSURLRequest requestWithURL:self.URL]];
        
        return;
    }
    
    if (self.urlString) {
        
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
    }
}

- (NSString *)mimeTypeForFileAtPath:(NSString *)path{
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        return nil;
    }
    
    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[path pathExtension], NULL);
    CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
    CFRelease(UTI);
    if (!MIMEType) {
        return @"application/octet-stream";
    }
    return (__bridge NSString *)(MIMEType);
}

#pragma mark - <webviewDelegate>
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
    webView.scrollView.showsVerticalScrollIndicator = !_hideIndicator;
    !self.loadStartBlock ? : self.loadStartBlock(self);
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
    !self.loadFinishedBlock ? : self.loadFinishedBlock(self);
    
    if (self.navigationItem.title) return;
    
    self.navigationItem.title = webView.title;
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"%@", error);
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    decisionHandler(WKNavigationActionPolicyAllow);
    
    NSLog(@"%d", webView.canGoBack);
}

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

#pragma mark - scollViewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    !self.tableViewDidEndDraggingBlock ? : self.tableViewDidEndDraggingBlock(scrollView.contentOffset);
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    self.webView.scrollView.delegate = nil;
    
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    //    [self.webView removeObserver:self forKeyPath:@"canGoBack"];
    NSLog(@"%d, %s",__LINE__, __func__);
}

@end
